package com.lge.qcontact;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lge.qcontact.utils.LocalDBHelper;

/**
 * 
 * @author project
 * GroupListActivity로부터 넘겨받은 group명을 이용하여
 * DB를 검색하여 해당 group의 멤버의 연락처 정보 list를 출력.
 * ListView의 각 Item 칸에 표시될 custom layout은 xml파일로 따로 작성한다.
 */
public class ContactListActivity extends Activity implements Runnable{
	
	private ArrayList<String> Namelist;
	private ArrayList<String> Phonelist;
	private ArrayList<String> Emaillist;
	private ArrayList<String> Mobilelist;
	private ArrayList<String> Idlist;
	private ArrayList<Integer> Photolist;
	
	
	private ListView list;
	private int index = 0;
	private ContractAdapter adapter;
	
	private Handler handler = new Handler(){
		
		public void handleMessage(Message msg)
		{
			list.setAdapter(new ContractAdapter(ContactListActivity.this, Namelist, Phonelist, Emaillist, Mobilelist, Idlist, Photolist));
		}	
	};
		
	private String result1 = null;
	private String result2 = null;
	private String result3 = null;
	private String result4 = null;
	private String result5 = null;
	private String result6 = null;
	private String GroupName = null;
	private String uId = null;
	private Intent callintent;
	private Intent photointent;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_contact_list);
		Namelist = new ArrayList<String>();
		Phonelist = new ArrayList<String>();
		Emaillist = new ArrayList<String>();
		Mobilelist = new ArrayList<String>();
		Idlist = new ArrayList<String>();
		Photolist = new ArrayList<Integer>();
		
		list = (ListView)findViewById(R.id.list);
		
		Intent intent = getIntent();
		GroupName = intent.getStringExtra("groupName");
		uId = intent.getStringExtra("uid");
		
		
		new Thread(this).start();
		
		
		LayoutInflater inflater = getLayoutInflater();
		
		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				
				AlertDialog.Builder builder = new AlertDialog.Builder(ContactListActivity.this);
				final int position = arg2;
				builder.setTitle(Namelist.get(arg2)+"님의 연락처")
					   .setMessage("수행할 작업을 선택해 주십시오")
					   .setNegativeButton("전화걸기", new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							callintent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:"+Mobilelist.get(position)));
							startActivity(callintent);
							
						}
					})
						.setNeutralButton("사진설정", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							photointent = new Intent(ContactListActivity.this, PhotoActivity.class);
							photointent.putExtra("uid", Idlist.get(position));
							photointent.putExtra("GroupName", GroupName);
							startActivity(photointent);
							}
					})
					.setPositiveButton("취소", new DialogInterface.OnClickListener() {
						
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					})
					.show();	
					}
		});
		
	}
	
	

	protected void onPause() {
		finish();
		super.onPause();
	}

	

	public void run() {
//		try {
//			URL url = new URL(
//					"http://192.168.0.205:8080/com.lg.project.myexample.cmd.RetrieveMemberUserJoinListCmd.vcc");
//
//			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
//			XmlPullParser parser = factory.newPullParser();
//			parser.setInput(url.openStream(), "utf-8");
//			int eventType = parser.getEventType();
//			while (eventType != XmlPullParser.END_DOCUMENT) {
//				switch (eventType) {
//				case XmlPullParser.START_DOCUMENT:
//					break;
//				case XmlPullParser.START_TAG:
//					if (parser.getName().equals("uid")) {
//						result1 = parser.nextText();
//						Namelist.add(result1);
//						Log.i("uid : ", result1);
//					} else if (parser.getName().equals("uname")) {
//						result6 = parser.nextText();
//						Idlist.add(result6);
//						Log.i("uname", result6);
//					} else if (parser.getName().equals("email")) {
//						result2 = parser.nextText();
//						Emaillist.add(result2);
//					} else if (parser.getName().equals("mobile")) {
//						result3 = parser.nextText();
//						Mobilelist.add(result3);
//					} else if (parser.getName().equals("phoneno")) {
//						result4 = parser.nextText();
//						Phonelist.add(result4);
//					} else if (parser.getName().equals("gname")) {
//						result5 = parser.nextText();
//						if (!(result5.equals(GroupName)))// 그룹네임이 들어가야 함
//						{
//							Namelist.remove(index);
//							Emaillist.remove(index);
//							Mobilelist.remove(index);
//							Phonelist.remove(index);
//							Idlist.remove(index);
//							index--;
//						}
//						index++;
//					}
//					break;
//				case XmlPullParser.END_TAG:
//					break;
//				}
//				eventType = parser.next();
//			}
//		} catch (MalformedURLException e) {
//			e.printStackTrace();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		handler.sendEmptyMessage(0);
		
		String sql = "select uName, uId, email, phoneNo, mobile, photoId from CONTACTS " +
				"where gname='" + GroupName + "';";
		
		SQLiteDatabase localDB = (new LocalDBHelper(ContactListActivity.this)).getWritableDatabase();
		Cursor c = localDB.rawQuery(sql, null);
		
		while(c.moveToNext()){
			Namelist.add(c.getString(0));
			Idlist.add(c.getString(1));
			Log.d("uid", c.getString(1));
			Emaillist.add(c.getString(2));
			Phonelist.add(c.getString(3));
			Mobilelist.add(c.getString(4));
			Photolist.add(c.getInt(5));
			Log.i("Photolist : ", ""+c.getInt(5));
			
		}
		
		handler.sendEmptyMessage(0);
	}
}
	

class ContractAdapter extends BaseAdapter
{
	private ArrayList<String> Namelist;
	private ArrayList<String> Phonelist;
	private ArrayList<String> Emaillist;
	private ArrayList<String> Mobilelist;
	private ArrayList<String> Idlist;
	private ArrayList<Integer> Photolist;
	private Activity mContext;
	
	
	ContractAdapter(Activity context, ArrayList<String> Name, ArrayList<String> Phone, 
			ArrayList<String> Email, ArrayList<String> Mobile, ArrayList<String> Id, ArrayList<Integer> Photo)
	{
		mContext = context;
		Namelist = new ArrayList<String>();
		Phonelist = new ArrayList<String>();
		Emaillist = new ArrayList<String>();
		Mobilelist = new ArrayList<String>();
		Idlist = new ArrayList<String>();
		Photolist = new ArrayList<Integer>();
		
		Namelist = Name;
		Phonelist = Phone;
		Emaillist = Email;
		Mobilelist = Mobile;
		Idlist = Id;
		Photolist = Photo;
		
	}
	
	public int getCount() {
		
		return Namelist.size();
	}

	
	public Object getItem(int arg0) {
		
		return null;
	}

	
	public long getItemId(int arg0) {
		
		return 0;
	}

	
	public View getView(int position, View arg1, ViewGroup arg2) {
		View row = arg1;
		if(row == null)
		{
			LayoutInflater inflater = mContext.getLayoutInflater();
			row = inflater.inflate(R.layout.activity_contact_list2, null);
		}
		ImageView Image = (ImageView)row.findViewById(R.id.imageview);
		if(Photolist.get(position) == 0)
		{
			Image.setImageResource(R.drawable.img_noimage);			
		}
		else 
		{
			Image.setImageResource(Photolist.get(position));
		}
		TextView Name = (TextView)row.findViewById(R.id.Namelist);
		Name.setText(Idlist.get(position)+"("+Namelist.get(position)+")");
		TextView Phone = (TextView)row.findViewById(R.id.Phonelist);
		Phone.setText(Phonelist.get(position));	
		TextView Email = (TextView)row.findViewById(R.id.Emaillist);
		Email.setText(Emaillist.get(position));	
		TextView Mobile = (TextView)row.findViewById(R.id.Mobilelist);
		Mobile.setText(Mobilelist.get(position));
		return row;
	}
	
}
